<?php

namespace App\Http\Controllers\Tools;

use App\Blocks\Goods;
use App\Models\Product;
use App\Models\User;
use Illuminate\Http\Request;

class CouponController extends ToolsController {

    public function addEvaluateView(){
        return view('tools.add-evaluate');
    }

    public function couponView($key){

        $data = \Cache::get($key);

        $data['coupon_start'] = date('Y-m-d', strtotime('-7day'));
        $data['coupon_end'] = date('Y-m-d', strtotime('+7day'));
        $data['coupon_price'] = (int)($data['price'] / 3);
        $data['end_price'] = $data['price'] - $data['coupon_price'];

        return view('tools.coupon', $data);
    }

    public function couponImg(Request $request){
        $key = 'coupon-view-key-'.uniqid();
        \Cache::put($key, $request->all(), 1);
        $url = 'http://'.$_SERVER['HTTP_HOST'].'/tool/coupon/view/'.$key;
        $cmd = "/usr/bin/phantomjs " .public_path()."/tool/coupon/phantom.js " . $url;
        $res = exec($cmd);
        if($res){
            $imgData = base64_decode($res);

            $dir = public_path().'/imgs/coupon';
            $fileName = uniqid().'.jpeg';

            if(!is_dir($dir)){
                @mkdir($dir, 0755 , true);
            }

            file_put_contents($dir.'/'.$fileName , $imgData);
//            downloadFile($dir.'/'.$fileName, '优惠券.jpeg');
            return response()->json(['url' => '/imgs/coupon/'.$fileName]);
        }else{
            return response()->json(['error' => 'product img faild']);
        }
    }

    public function goodsExtImgView($key , Request $request){
        $data = \Cache::get( $key );
        $data = [
            'slogan'        => '唯美浪漫；前卫设计款型，腰部别致褶涧，名媛小香风，条纹显瘦长裙沙滩裙，360度大摆',
            'title'         => '白色秋冬新款韩版开叉学生半高领套头毛衣女短款宽松针织衫打底衫',
            'coupon_price'  => '10',
            'goods_img'     => 'https://gd3.alicdn.com/imgextra/i1/2831531036/TB2BGp4yH4npuFjSZFmXXXl4FXa_!!2831531036.jpg_400x400.jpg',
            'goods_price'   => '102.56',
            'qrcode'        => '/qrcode/showqrcode.jpg'
        ];

        if(empty($data)){
            return abort(404);
        }
        return view('tools.goods_ext_img' , $data);
    }

    public function goodsExtImg2View($goodsId, Request $request){
        $goodsBlock = new Goods();
        $data = $goodsBlock->getGoodsInfo($goodsId);
        if(empty($data)){
            return abort(404);
        }

        $qrcodeName = $goodsId.'-'.time().'.png';

        $type = null;
        $wechat = null;
        $agentId = null;

        $cacheKey = $request->get('cache');
        $cache = \Cache::get($cacheKey);
        if(isset($cache['type'])){
            $type = $cache['type'];
        }
        if(isset($cache['agent'])){
            $agentId = $cache['agent'];
        }
        if(isset($cache['wechat'])){
            $wechat = $cache['wechat'];
        }

        $qrcodeUrl = env('WEB_URL')."/goods/info/{$data->tbid}/wechatimg";

        if($type == 'login'){
            $qrcodeUrl = env('APP_URL')."/api/wechat/login?appid={$wechat}&redirect=goodsshare&agent={$agentId}&goodsid={$data->tbid}";
        }

        /**
         * generate里面的域名要允许跨域
         */
        \QrCode::format('png')
            ->size(300)
            ->margin(0)
            ->encoding('UTF-8')
            ->generate($qrcodeUrl , public_path('qrcode/'.$qrcodeName) , 'image/png');

        $data->qrcode = "/qrcode/{$qrcodeName}";
        return view('tools.goods_ext_img2' , (Array)$data);
    }

    public function goodsExtImg2($goodsId, Request $request){
        try {
            $type = null;
            $wechat = null;
            $agentId = null;

            $repType = $request->get('repType', 'down');

            if($request->has('type')){
                $type = $request->get('type');
            }

            if($request->has('token')){
                $token = $request->get('token');
                if($token == 'test123') {
                    $userInfo = User::where('id', 1)->first();
                }
                else{
                    $userInfo = \Cache::get($token);
                }
                if($userInfo){
                    $agentId = $userInfo->id;
                }
            }

            if($type === 'login'){
                $wechat = env('SHARE_WECHAT_LOGIN');
            }

            $product = Product::where('tbid', $goodsId)->first();

            if (!$product) {
                return response()->json(['error' => 'product not exist']);
            }

            $dir = public_path() . '/imgs/goods';
            if (!is_dir($dir)) {
                @mkdir($dir, 0755, true);
            }

            $fileName = uniqid() . '.jpeg';

            $cackeKey = uniqid();
            $cacheData = [
                'wechat' => $wechat,
                'agent' => $agentId,
                'type' => $type
            ];
            \Log::debug($cacheData);
            \Cache::put($cackeKey, $cacheData, 1);
            $url = "http://{$_SERVER['HTTP_HOST']}/tool/goods/ext/img2/view/{$product->tbid}?cache={$cackeKey}";
            $cmd = "/usr/bin/phantomjs " . public_path() . "/phantom.js " . $url;
            $res = exec($cmd);
            if (!$res) {
                return response()->json(['error' => 'product img faild']);
            }
            $imgData = base64_decode($res);

            file_put_contents($dir . '/' . $fileName, $imgData);
            if($repType == 'json') {
                return response()->json(['url' => 'http://'.$request->getHost()."/imgs/goods/{$fileName}"]);
            }else {
                downloadFile($dir . '/' . $fileName, $product->goods_name . '.jpeg');
            }
        }catch (\Exception $e){
            \Log::error($e);
            return response()->json(['error' => 'unknown error']);
        }
    }
}